package com.gcxy.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.poi.xwpf.usermodel.*;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.util.ClassUtil.getClassLoader;

/**
 * @author qinlun
 * @date 2023/9/15
 * <p>
 * Word导出工具类
 */
public class XWPFUtil {

    /**
     * 替换段落里面的变量
     *
     * @param document   要替换的文档
     * @param contentMap 参数
     */
    public static void replaceInPara(XWPFDocument document, Map<String, Object> contentMap) {
        // 替换段落中的指定文字
        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            XWPFParagraph paragraph = itPara.next();
            commonCode(paragraph, contentMap);
        }

        // 替换表格中的指定文字
        Iterator<XWPFTable> itTable = document.getTablesIterator();
        while (itTable.hasNext()) {
            XWPFTable table = itTable.next();
            int rcount = table.getNumberOfRows();
            for (int i = 0; i < rcount; i++) {
                XWPFTableRow row = table.getRow(i);
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    //单元格中有段落，得做段落处理
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        commonCode(paragraph, contentMap);
                    }
                }
            }
        }

    }

    /**
     * 替换段落里面的变量
     *
     * @param paragraph  要替换的段落
     * @param contentMap 参数
     */
    private static void commonCode(XWPFParagraph paragraph, Map<String, Object> contentMap) {
        List<XWPFRun> runs = paragraph.getRuns();
        for (XWPFRun run : runs) {
            String oneparaString = run.getText(run.getTextPosition());
            if (StringUtils.isBlank(oneparaString) || !oneparaString.contains("${")) {
                continue;
            }
            if (contentMap.get(oneparaString) != null) {
                if (contentMap.get(oneparaString).toString().contains("\n")) {
                    String[] lines = contentMap.get(oneparaString).toString().split("\n");
                    if (lines.length > 0) {
                        // set first line into XWPFRun
                        oneparaString = lines[0];
                        run.setText(oneparaString, 0);
                        for (int i = 1; i < lines.length; i++) {
                            // add break and insert new text
                            run.addBreak();
                            run.setText(lines[i]);
                        }
                    }
                } else {
                    oneparaString = oneparaString.replace(oneparaString, (String) contentMap.get(oneparaString));
                    run.setText(oneparaString, 0);
                }
            } else {
                String[] s = oneparaString.split("：");
                String semester = s[s.length - 1];
                String newSemester = s[0] + "：" + contentMap.get(semester);
                oneparaString = oneparaString.replace(oneparaString, newSemester);
                run.setText(oneparaString, 0);
            }
        }
    }

    /**
     * 生成教师周指导记录word文件
     */
    public static void createWord(List<String> targetPaths, Map<String, Object> map) {
        try {
            InputStream inputStream = getClassLoader().getResourceAsStream("教师周指导记录.docx");
            XWPFDocument document = new XWPFDocument(inputStream);
            XWPFUtil.replaceInPara(document, map);
            for (String targetPath : targetPaths) {
                String folderName = targetPath.substring(0, targetPath.lastIndexOf("/"));
                File file = new File(folderName);
                if (!file.exists()) {
                    file.mkdirs();
                }
                document.write(Files.newOutputStream(Paths.get(targetPath)));
            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成学生周报word文件
     * @param targetPath
     * @param map
     */
    public static void createWeeklyWord(String targetPath, Map<String, Object> map) {
        try {
            InputStream inputStream = getClassLoader().getResourceAsStream("学生周报.docx");
            XWPFDocument document = new XWPFDocument(inputStream);
            XWPFUtil.replaceInPara(document, map);
            String folderName = targetPath.substring(0, targetPath.lastIndexOf("/"));
            File file = new File(folderName);
            if (!file.exists()) {
                file.mkdirs();
            }
            document.write(Files.newOutputStream(Paths.get(targetPath)));
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
